<?php
if(!defined('EntryPoint')) die; // protection

/* ========================================
 * --------------------
 *  App.php
 * --------------------
 * Created on 22.03.2010
 * ========================================
 * $Revision: $
 * $Author: Dmitry Boycov
 * $HeadURL: $
 * $Id: $
 * ========================================
 * Changes ["date: description (who)"]:
 *
 * 22.03.2010: Original version (WHo)
 * 15:21:00: Time
 */
require_once("include/bd/DataBase.php");

class App {

	private static $Settings = array();

	private static $module = '';

	private static $db = null;
    //private static $Session;

	//private static $SessionId;

	private static $Request;

	public static function db(){
        return self::$db;
    }

    public static function settings($key = null) {
		if($key == null){
			return self::$Settings;
		}else{
			if(array_key_exists($key,self::$Settings)){
				return self::$Settings[$key];
			}else{
				return null; 
			}
		}
	}

	public static function request($key = null){
		if($key == null){
			return self::$Request;
		}else{
			if(array_key_exists($key,self::$Request)){
				return self::$Request[$key];
			}else{
				return null;
			}
		}
	}


	public static function module(){
		return self::$module;
	}

//	public static function session(){
//		return self::$Session;
//	}

	private static function loadSettings($path) {
		try {
			include_once realpath($path);
			return get_defined_vars();
		} catch(Exception $e) {
			throw new ConfigurationError("could not read primary configuration file '{$path}': {$e->getMessage()}");
		}
	}

	/**
	 * init settings, request
	 * @static
	 * @return void
	 */
	public static function init(){
		self::$Request = $_REQUEST;
		unset($_REQUEST);
		unset($_GET);
		unset($_POST);
//		self::$Session = $_SESSION;
		self::$Settings = self::loadSettings('config.php');
		$appPath = realpath('.');
		self::$Settings['APP_PATH'] = $appPath; 
	}

	public static function run(){
		$startTime = microtime();
		session_start();
		ob_start();
		self::init();
		self::$module = trim($_SERVER['PATH_INFO'],'/');
		if(empty(self::$module) ||  self::$module==''){
			if(!empty(self::$Request['module'])){
				self::$module = self::$Request['module'];
			}else{
				self::$module = self::$Settings['defaultModule'];
			}
		}
		// protection against re direction 
		if(!in_array(self::$module,self::$Settings['module'])){
			self::$module = self::$Settings['defaultModule'];
		}
        // connect
        $connectParam = self::settings("db");
        self::$db = new DataBase($connectParam['host'],$connectParam['user'],$connectParam['pwd'],$connectParam['name']);
        self::$db->connect();
	}

	public static function destroy(){
		// clean service information
        //disconnect
        self::$db->close();
	}
	
}